package com.FOD.fragments;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import com.FOD.clases.R;
import com.FOD.clases.globalFunctions;
import com.FOD.entities.EmpleadoHorario;
import com.FOD.entities.User;
import com.FOD.util.SessionDBHandler;
import com.FOD.web.UsersFunctions;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewManager;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;


public class EditUserEmployeFragment extends Fragment {
	View rootView;
	EditText nickname_edit;
	EditText name_edit;
	EditText last_name_edit;
	EditText mail_edit;
	EditText age_edit;
	Spinner sex_edit;
	EditText dependency_edit;
	EditText sport_edit;
	EditText phone_edit;
	TimePicker timeIn_edit;
	TimePicker timeOut_edit;
	Button editAction;
	User mUser;
	EmpleadoHorario mEmpleadoHorario;
	UsersFunctions userFunctions = new UsersFunctions();
	globalFunctions globalFunctions = new globalFunctions();
	SessionDBHandler db;
	ProgressDialog pDialog;

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.edit_user_empleado, container, false);
		db = new SessionDBHandler(rootView.getContext());

		nickname_edit = (EditText)rootView.findViewById(R.id.nickname_edit);
		name_edit = (EditText) rootView.findViewById(R.id.name_edit);
		mail_edit = (EditText)rootView.findViewById(R.id.mail_edit);
		age_edit = (EditText)rootView.findViewById(R.id.age_edit);
		sex_edit = (Spinner)rootView.findViewById(R.id.sex_edit);
		dependency_edit = (EditText)rootView.findViewById(R.id.dependency_edit);
		sport_edit = (EditText)rootView.findViewById(R.id.sport_edit);
		phone_edit = (EditText)rootView.findViewById(R.id.phone_edit);
		timeIn_edit = (TimePicker)rootView.findViewById(R.id.timeIn_edit);
		timeOut_edit = (TimePicker)rootView.findViewById(R.id.timeOut_edit);
		editAction = (Button)rootView.findViewById(R.id.editAction);

		//Asignar valores de sexo al Spinner sex_new
		ArrayAdapter<CharSequence> adapter_sexType = ArrayAdapter.createFromResource(rootView.getContext(),R.array.sex_types_spinner, android.R.layout.simple_spinner_item);
		sex_edit.setAdapter(adapter_sexType);

		SessionDBHandler db = new SessionDBHandler(rootView.getContext());
		mUser = db.getUserDetails();

		nickname_edit.setText(mUser.getNickname());
		name_edit.setText(mUser.getName());
		mail_edit.setText(mUser.getMail());
		age_edit.setText(String.valueOf(mUser.getAge()));
		sex_edit.setSelection(mUser.getSex());
		dependency_edit.setText(mUser.getDependecy());
		sport_edit.setText(mUser.getSport());
		phone_edit.setText(String.valueOf(mUser.getPhone()));

		mEmpleadoHorario = db.getScheduleEmployeDetails();

		String hourIn = mEmpleadoHorario.getInicio().substring(0, 2);
		String minutesIn = mEmpleadoHorario.getInicio().substring(3, 5);
		timeIn_edit.setCurrentHour(Integer.valueOf(hourIn));
		timeIn_edit.setCurrentMinute(Integer.valueOf(minutesIn));

		String hourOut = mEmpleadoHorario.getH_final().substring(0, 2);
		String minutesOut = mEmpleadoHorario.getH_final().substring(3, 5);
		timeOut_edit.setCurrentHour(Integer.valueOf(hourOut));
		timeOut_edit.setCurrentMinute(Integer.valueOf(minutesOut));

		editAction.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				mUser.setNickname(nickname_edit.getText().toString());
				mUser.setName(name_edit.getText().toString());
				mUser.setMail(mail_edit.getText().toString());
				mUser.setAge(Integer.valueOf(age_edit.getText().toString()));
				mUser.setSex(mUser.getConverterSexToInt(sex_edit.getSelectedItem().toString(), rootView.getContext()));
				mUser.setDependecy(dependency_edit.getText().toString());
				mUser.setSport(sport_edit.getText().toString());
				mUser.setPhone(Integer.valueOf(phone_edit.getText().toString()));
				new editUser().execute(mUser, mEmpleadoHorario);
			}
		});

		return rootView;
	}

	private class editUser extends AsyncTask<Object, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(Object... params) {
			User userToInsert = (User) params[0];
			EmpleadoHorario mEmpleadoHorario = (EmpleadoHorario) params[1];
			return userToEdit(userToInsert, mEmpleadoHorario);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
		}

		@Override
		protected void onPreExecute() {
			pDialog = new ProgressDialog(rootView.getContext());
			pDialog.setMessage("Editando usuario...");
			pDialog.setCancelable(false);
			pDialog.show();
		}

		public Boolean userToEdit(User userToEdit, EmpleadoHorario empleadoHorarioToEdit){
			JSONObject json = userFunctions.editUser(userToEdit);
			try {
				if(json.getInt("error") == 0){

					JSONObject json_user = json.getJSONObject("user");

					String minutesIn = "";
					if(timeIn_edit.getCurrentMinute() >=0 && timeIn_edit.getCurrentMinute() < 10){
						minutesIn = "0"+String.valueOf(timeIn_edit.getCurrentMinute());
					}else{
						minutesIn = String.valueOf(timeIn_edit.getCurrentMinute());
					}
					String hourIn = "";
					if(timeIn_edit.getCurrentHour() >=0 && timeIn_edit.getCurrentHour() < 10){
						hourIn = "0"+String.valueOf(timeIn_edit.getCurrentHour());
					}else{
						hourIn = String.valueOf(timeIn_edit.getCurrentHour());
					}


					String minutesOut = "";
					if(timeOut_edit.getCurrentMinute() >=0 && timeOut_edit.getCurrentMinute() < 10){
						minutesOut = "0"+String.valueOf(timeOut_edit.getCurrentMinute());
					}else{
						minutesOut = String.valueOf(timeOut_edit.getCurrentMinute());
					}
					String hourOut = "";
					if(timeOut_edit.getCurrentHour() >=0 && timeOut_edit.getCurrentHour() < 10){
						hourOut = "0"+String.valueOf(timeOut_edit.getCurrentHour());
					}else{
						hourOut = String.valueOf(timeOut_edit.getCurrentHour());
					}

					mEmpleadoHorario.setId(json_user.getInt("id"));
					mEmpleadoHorario.setInicio(hourIn+":"+minutesIn);
					mEmpleadoHorario.setH_final(hourOut+":"+minutesOut);

					JSONObject json_employe = userFunctions.editEmploye(mEmpleadoHorario);
					json_employe = json_employe.getJSONObject("user");

					setUserToMemory(json_user);
					setEmployeToMemory(json_employe);
					db.close();
				}else{
					Toast.makeText(rootView.getContext(), "Ocurrio un error al agregar el usuario", Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (pDialog.isShowing()){
				pDialog.dismiss();
			}
			if(result){
				Toast.makeText(rootView.getContext(), "El usuario se ha editado con exito", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(rootView.getContext(), "Ocurrio un error al editar el usuario", Toast.LENGTH_SHORT).show();
			}
			globalFunctions.closeKeyboard(rootView.getContext(), rootView.getWindowToken());
			Fragment fragment = new HomeFragment();
			FragmentManager fragmentManager = getFragmentManager();
			fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).addToBackStack("aaa").commit();
		}
	}

	public void setUserToMemory(JSONObject json_user){
		db.resetTables();
		User mUser = new User();
		try {
			mUser.setId(json_user.getInt("id"));
			mUser.setNickname(json_user.getString("nickname"));
			mUser.setPassword(json_user.getString("password"));
			mUser.setName(json_user.getString("name"));
			mUser.setMail(json_user.getString("mail"));
			mUser.setType(json_user.getInt("user_type"));
			mUser.setAge(json_user.getInt("age"));
			mUser.setSex(json_user.getInt("sex"));
			mUser.setDependecy(json_user.getString("dependency"));
			mUser.setSport(json_user.getString("sport"));
			mUser.setPhone(Long.valueOf((json_user.getInt("phone"))));
			SimpleDateFormat dateFormatOfStringInDB = new SimpleDateFormat("yyyy-MM-dd");
			try {
				Date d1 = dateFormatOfStringInDB.parse(json_user.getString("create_date"));
				mUser.setCreateDate(d1);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			db.addUser(mUser);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void setEmployeToMemory(JSONObject json_employee){
		EmpleadoHorario eh = new EmpleadoHorario();

		try {
			eh.setId(json_employee.getInt("id"));
			eh.setUsuario_id(json_employee.getInt("usuario_id"));
			eh.setInicio(json_employee.getString("inicio"));
			eh.setH_final(json_employee.getString("final"));
			db.addScheduleEmploye(eh);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	//Hide the keyboard when the Fragmenet is created
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
	}

}
